<template>
	<view class="mine">
		<view class="mine-head">
			<view class="info-top" @click="toSetInfo">
				<image v-if="avatarUrl" class="img" :src="avatarUrl"></image>
				<image v-else class="img" src='@/img/new/moren.png'></image>
				<view style="flex: 1;">
					<view class="name">你好,{{ nickName || "游客" }}</view>
					<view class="phone-wrapper">
						<image class="phone-icon" src="@/img/yangcan/ic_phone_solid.png"></image>
						<view class="phone">{{ maskPhoneNumber || "--" }}</view>
					</view>
				</view>
				<u-icon class="arrow-right" name="arrow-right" color="#FFFFFF" size="40"></u-icon>
			</view>
			<view class="info-content">
				<view class="info-box">
					<view class="info-box-item">
						<view class="label">性别</view>
						<view class="value-wrapper">
							<view class="value">{{ gender || "--" }}</view>
						</view>
					</view>
					<view class="info-box-item">
						<view class="label">体重</view>
						<view class="value-wrapper">
							<view class="value">{{ weight || "--" }}</view>
							<view class="unit">kg</view>
						</view>
					</view>
					<view class="info-box-item">
						<view class="label">年龄</view>
						<view class="value-wrapper">
							<view class="value">{{ age || "--" }}</view>
							<view class="unit">岁</view>
						</view>
					</view>
					<view class="info-box-item">
						<view class="label">身高</view>
						<view class="value-wrapper">
							<view class="value">{{ height || "--" }}</view>
							<view class="unit">cm</view>
						</view>
					</view>
				</view>
				<view v-if="medHistoryList.length == 0" class="data-null">
					<image src="/img/yangcan/noData.png" style="width: 36rpx;height: 36rpx;padding-right: 10rpx;"></image>
					暂无病史
				</view>
				<scroll-view v-else scroll-x class="info-list">
					<view class="info-list-item" v-for="(item ,index) in medHistoryList" :key="index">
						{{ item.medicalName }}
					</view>
				</scroll-view>
			</view>
		</view>
		<view v-if="medHistoryList.length > 0" class="box">
			<view class="box-title">
				<view class="name">吸氧建议</view>
			</view>
			<view class="box-content">
				<image class="box-content-bg" :src="$IMAGE_BASE_URL3 + '/bg_suggest.png'"></image>
				<view class="table-title">
					<image class="table-title-icon" src="@/img/yangcan/ic_suggest.png"></image>
					<view class="table-title-text">根据您的病史，我们提供以下吸氧时间建议，仅供参考。</view>
				</view>
				<view class="table-container">
					<view class="table-header">
						<view class="table-cell">病史</view>
						<view class="table-cell">次数</view>
						<view class="table-cell" style="flex: 1.5;">改善情况</view>
					</view>
					<view class="table-body">
						<view v-if="medHistoryList.length > 0" class="table-row" v-for="(item, index) in medHistoryList"
							:key="index">
							<view class="table-cell">{{ item.medicalName }}</view>
							<view class="table-cell">{{ item.adviceCount }}</view>
							<view class="table-cell" style="flex: 1.5;">{{ item.effect }}</view>
						</view>
						<view v-else class="data-null" style="border-radius: 0 0 20rpx 20rpx;">
							<image src="/img/yangcan/noData.png" style="width: 36rpx;height: 36rpx;padding-right: 10rpx;"></image>
							暂无建议
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="box">
			<view class="box-title">
				<view class="name">预约管理</view>
			</view>
			<view class="box-content" @click="toReservationRecord">
				<template v-if="reservationList.length > 0">
					<view class="reservation-item" v-for="(item, index) in reservationList" :key="index">
						<view class="title-wrapper">
							<view class="circle"></view>
							<view class="title">{{ item.typeName }}</view>
						</view>
						<view class="statistics">
							<view class="statistics-item" v-for="(v, i) in item.list" :key="i">
								<view class="label">{{ v.state }}</view>
								<view class="value-wrapper">
									<view class="value">{{ v.count || 0 }}</view>
									<view class="unit">次</view>
								</view>
							</view>
							<!-- <view class="statistics-item">
								<view class="label">待核销</view>
								<view class="value-wrapper">
									<view class="value">0</view>
									<view class="unit">次</view>
								</view>
							</view>
							<view class="statistics-item">
								<view class="label">已核销</view>
								<view class="value-wrapper">
									<view class="value">0</view>
									<view class="unit">次</view>
								</view>
							</view>
							<view class="statistics-item">
								<view class="label">剩余量</view>
								<view class="value-wrapper">
									<view class="value">0</view>
									<view class="unit">次</view>
								</view>
							</view> -->
						</view>
					</view>
				</template>
				<template v-else>
					<view class="data-null">
						<image src="/img/yangcan/noData.png" style="width: 36rpx;height: 36rpx;padding-right: 10rpx;"></image>
						暂无预约数据
					</view>
				</template>
			</view>
		</view>
		<view class="box">
			<view class="box-title">
				<view class="name">报警管理</view>
			</view>
			<view class="box-content">
				<view class="manager-item" @click="toAlarm">
					<view class="manager-icon">
						<image src="@/img/yangcan/ic_warn_set.png" mode="heightFix">
						</image>
					</view>
					<view class="manager-info">
						<view class="name">报警阈值设置</view>
					</view>
					<u-icon class="manager-arrow" name="arrow-right" color="#000" size="40"></u-icon>
				</view>
			</view>
		</view>
		<view class="box">
			<view class="box-title">
				<view class="name">设备管理</view>
				<!-- <view class="add">
					<image src="@/img/yangcan/ic_add.png"></image>
				</view> -->
			</view>
			<view class="box-content">
				<template v-if="deviceList.length > 0">
					<view class="device-item" v-for="(item, index) in deviceList" :key="index">
						<view class="device-icon">
							<image v-if="item.deviceType == 'W_OXYGEN'" src="@/img/yangcan/ic_yangcan.png"
								mode="heightFix">
							</image>
							<image v-else src="@/img/yangcan/ic_light.png" mode="heightFix">
							</image>
							<!-- 	<image v-else-if="item.deviceType == 'LIGHT'" src="@/img/yangcan/ic_light.png"
								mode="heightFix">
							</image> -->
						</view>
						<view class="device-info">
							<view class="name">设备管理</view>
							<view class="number">设备号: {{ item.deviceName }}</view>
						</view>
						<view class="delete-btn-wrapper" @click="onUnbindDevice(item)">
							<view class="delete-btn">移除设备</view>
						</view>
					</view>
				</template>
				<template v-else>
					<view class="data-null">
						<image src="/img/yangcan/noData.png" style="width: 36rpx;height: 36rpx;padding-right: 10rpx;"></image>
						暂无设备
					</view>
				</template>
			</view>
		</view>
		<view style="height: 148rpx;"></view>
		<Tabbar :selected="2" />

		<ReservationPopup title="提示" :content="unbindContent" type="dialog" :show="isShow" @updateShow="e => isShow = e"
			@cancel="onCancelUnbind" @confirm="onConfirmUnbind" />
	</view>
</template>

<script>
	import * as LoginApi from '@/api/login/index.js';
	import * as UserApi from '@/api/user';
	import * as DeviceApi from '@/api/device/index.js';
	import * as ReservationApi from '@/api/reservation/index.js';
	import StorageUtils from "@/utils/StorageUtils";
	import CacheConfig from '@/config/CacheConfig.js';
	import ReservationPopup from '@/components/reservation-popup/index.vue';
	import {
		showInfo
	} from '@/utils/ToastUtils.js';

	const orderNavbar = [
		// { id: 'all', name: '全部订单', icon: '/static/order-1.png' },
		// { id: 'payment', name: '待支付', icon: '/static/order-2.png', count: 0 },
		// { id: 'delivery', name: '待发货', icon: '/static/order-3.png', count: 0 },
		// { id: 'received', name: '待收货', icon: '/static/order-4.png', count: 0 },
	]

	export default {
		data() {
			return {
				orderNavbar: [{
						id: 'all',
						name: '全局订单',
						icon: this.$IMAGE_BASE_URL + '/static/ic_order_1.png'
					},
					{
						id: 'payment',
						name: '待付款',
						icon: this.$IMAGE_BASE_URL + '/static/ic_order_2.png',
						count: 0
					},
					{
						id: 'delivery',
						name: '待发货',
						icon: this.$IMAGE_BASE_URL + '/static/ic_order_3.png',
						count: 0
					},
					{
						id: 'received',
						name: '退款/售后',
						icon: this.$IMAGE_BASE_URL + '/static/ic_order_4.png',
						count: 0
					},
				],
				avatarUrl: "",
				nickName: "",
				gender: "",
				weight: "",
				height: "",
				birth: "",
				age: "",
				mobile: "",
				currentUuid: "",
				userId: "",
				medHistoryList: [],
				deviceList: [],
				childDevice: [],
				reservationList: [],
				selectedDevice: null,
				isShow: false,
			}
		},
		components: {
			ReservationPopup
		},
		onShow() {
			this.getPageData();
		},
		computed: {
			maskPhoneNumber() {
				if (!this.mobile) return '';
				const str = String(this.mobile).replace(/\s/g, '');
				if (!/^\d{11}$/.test(str)) {
					return this.mobile;
				}
				return str.substr(0, 3) + '****' + str.substr(7);
			},
			unbindContent() {
				if (!!this.selectedDevice && !!this.selectedDevice.deviceType) {
					if (this.selectedDevice.deviceType == 'LIGHT') {
						if(this.childDevice.length > 0) {
							const devices = this.childDevice.map(v => v.name);
							return `解绑星梦云康后，下设备 ${devices.join(",")} 将从当前账户移除，请确认是否解绑？`;
						} else {
							return "是否解绑该星梦云康设备";
						}
					} else if (this.selectedDevice.deviceType == 'W_OXYGEN') {
						return `是否解绑该氧舱设备`;
					}
				}
			},
		},
		methods: {
			getPageData() {
				if (StorageUtils.get(CacheConfig.TOKEN_KEY)) {
					this.getUserInfo();
				}
			},
			getUserInfo() {
				UserApi.info({
					'access_token': StorageUtils.get(CacheConfig.TOKEN_KEY)
				}, {
					load: true
				}).then(res => {
					console.log("userInfo res", res);
					if (res.obj) {
						const {
							avatarUrl,
							nickName,
							gender,
							birth,
							weight,
							height,
							age,
							mobile,
							uuid,
							id,
							medicalHistory,
						} = res.obj;
						this.avatarUrl = avatarUrl;
						this.nickName = nickName;
						this.gender = gender == 1 ? '男' : gender == 2 ? '女' : '';
						this.birth = birth;
						this.weight = weight;
						this.height = height;
						this.age = age;
						this.mobile = mobile;
						this.currentUuid = uuid;
						this.userId = id;
						this.medicalHistory = medicalHistory;

						this.getUserMedHistory();
						this.getDeviceList();
						this.getReservationTotal();
					}
				});
			},
			getUserMedHistory() {
				const arr = this.medicalHistory ? this.medicalHistory.split(",").map(v => Number(v)) : [];
				UserApi.getAllMedical().then(res => {
					console.log("getAllMedical", res);
					if (res.obj) {
						this.medHistoryList = res.obj.filter(v => arr.includes(v.id));
					}
				})
			},
			async getDeviceList() {
				try {
					const deviceTypeRes = await LoginApi.getDeviceType();
					console.log("getDeviceType", deviceTypeRes);
					const deviceType = deviceTypeRes.obj;
					const typeList = Object.entries(deviceType).map(([key, value]) => ({
						value: key,
						label: value.msg
					}));
					const res = await LoginApi.device({
						uuid: this.currentUuid
					});
					console.log("getDevice success", res.obj);
					this.deviceList = res && res.obj ? res.obj.map(device => {
						const {
							label
						} = typeList.find(type => type.value === device.deviceType) || {};
						return {
							...device,
							name: device.deviceType == 'LIGHT' ? '医康网关' : label
						};
					}) : [];
				} catch (err) {
					console.log("getDevice error", err);
				}
			},
			getReservationTotal() {
				ReservationApi.getReservationTotal(this.userId).then(res => {
					console.log("getReservationTotal res", res);
					this.reservationList = res.obj;
					this.reservationList.forEach(item => {
						item.list = [{
								state: '待核销',
								count: item.list.find(v => v.state == '已预约').count || 0,
							},
							{
								state: '已核销',
								count: item.list.find(v => v.state == '已核销').count || 0,
							},
							{
								state: '剩余额',
								count: item.list.find(v => v.state == '总预约').count || 0,
							}
						];
					})
				})
			},
			toSetInfo() {
				const token = StorageUtils.get(CacheConfig.TOKEN_KEY);
				if (token) {
					uni.navigateTo({
						url: '/pages/mine/personal'
					})
				} else {
					uni.navigateTo({
						url: '/pages/mine/authorize'
					})
				}
			},
			async onUnbindDevice(item) {
				console.log("onUnbindDevice item", item);
				if(item.deviceType == "LIGHT") {
					try {
						const propertRes = await DeviceApi.getPropert({deviceId: item.iotDeviceId});
						const propert = propertRes.obj;
						if(propert.work_mode.value == 1) {
							showInfo("请先退出夜灯模式！");
							return;
						}
						const childDeviceObj = propert['childDevices'];
						if (!childDeviceObj) return;
						let childDevice = childDeviceObj.value || "[]";
						childDevice = JSON.parse(childDevice);
						console.log("childDevice", childDevice);
						childDevice.forEach(item => {
							const device = this.deviceList.find(v => v.deviceName == item.mac);
							console.log("device", device);
							if(device) {
								item.name = device.name;
							}
						})
						console.log("childDevice", childDevice);
						this.childDevice = childDevice || [];
					} catch (e) {
						console.log("getPropert error", e);
					}
				}
				this.selectedDevice = item;
				this.isShow = true;
			},
			onCancelUnbind() {
				this.selectedDevice = null;
				this.isShow = false;
			},
			onConfirmUnbind() {
				const param = {
					deviceName: this.selectedDevice.deviceName,
					deviceType: this.selectedDevice.deviceType,
					uuid: -1,
				};
				const option = {
					isPrompt: false,
				};
				console.log('unbindConfirm param', param);
				DeviceApi.bindDevice(param, option).then(res => {
					if(this.selectedDevice.deviceType.startsWith('B')) {
						showInfo("解绑成功：请重启星梦云康");
					} else {
						showInfo("解绑成功");
					}
					this.isShow = false;
					const index = this.deviceList.findIndex(v => v.id == this.selectedDevice.id);
					if (index != -1) {
						this.deviceList.splice(index, 1);
					}
				}).catch(err => {
					console.log("bindDevice error", err);
					if(err.errMsg == 'Device is offline') {
						showInfo("解绑失败：星梦云康离线");
					}else if(err.errMsg == '超时') {
						showInfo("解绑失败：发送指令超时");
					}
				})
			},
			toReservationRecord() {
				if (!this.$isLogin()) return;
				uni.navigateTo({
					url: '/pages/oxygen/reservation-record'
				})
			},
			toAlarm() {
				if (!this.$isLogin()) return;
				uni.navigateTo({
					url: '/pages/mine/alarm'
				})
				// const msgId = 'wxAIVaFU0QAGNKevgbWPcki3P8fuRE2tQctuvGmW0O0';
				// uni.requestSubscribeMessage({
				// 	tmplIds: [msgId],
				// 	success: (res) => {
				// 		console.log("requestSubscribeMessage success", res);
				// 		if(res[msgId] == 'accept') {
				// 			console.log("用户同意订阅");
				// 		} else {
				// 			console.log("用户不同意订阅");
				// 		}
				// 		uni.navigateTo({
				// 			url: '/pages/mine/alarm'
				// 		})
				// 	},
				// 	fail: (err) => {
				// 		console.log("requestSubscribeMessage error", err);
				// 		showInfo(err.errMsg);
				// 	},
				// 	// complete: () => {
						
				// 	// }
				// })
			}
		}
	}
</script>

<style scoped lang="scss">
	.mine {
		padding: 0 30rpx;
		padding-top: 25rpx;
		padding-bottom: 44rpx;
		background-color: #f5f6f7;
		min-height: 100vh;
		font-family: PingFang;

		.mine-head {
			background-color: #ff790f;
			display: flex;
			flex-direction: column;
			border-radius: 20rpx;
			padding: 25rpx;
			box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);

			.info-top {
				display: flex;
				align-items: center;

				.img {
					width: 100rpx;
					height: 100rpx;
					border-radius: 100rpx;
					margin-right: 5rpx;
					// margin-right: 28rpx;
				}

				.name {
					font-family: PingFang;
					font-size: 45rpx;
					font-weight: bold;
					color: #040303;
					margin-left: 13rpx;
				}

				.phone-wrapper {
					width: 265rpx;
					height: 40rpx;
					border-radius: 40rpx;
					background-color: #ffb36d;
					display: flex;
					align-items: center;
					margin-top: 15rpx;

					.phone-icon {
						width: 29rpx;
						height: 29rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-left: 15rpx;
					}

					.phone {
						font-family: PingFang;
						font-size: 28rpx;
						font-weight: bold;
						color: #040303;
						margin-left: 15rpx;
					}
				}
			}

			.info-content {
				width: 643rpx;
				height: 248rpx;
				background-color: #fffbed;
				border-radius: 20rpx;
				margin-top: 28rpx;
				padding: 18rpx;
				box-sizing: border-box;

				.info-box {
					border-radius: 20rpx;
					overflow: hidden;
					display: flex;

					.info-box-item {
						flex: 1;
						height: 116rpx;
						margin-right: 2rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						background-color: #fdeddb;

						.label {
							font-size: 24rpx;
							color: #3e3e3e;
						}

						.value-wrapper {
							margin-top: 18rpx;
							display: flex;
							align-items: baseline;

							.value {
								font-size: 36rpx;
								color: #3e3e3e;
								font-weight: bold;
							}

							.unit {
								font-size: 24rpx;
								color: #3e3e3e;
								font-weight: bold;
								margin-left: 3rpx;
							}

						}

					}

					.info-box-item:last-child {
						margin-right: 0;
					}

				}

				.info-list {
					width: 100%;
					height: 102rpx;
					white-space: nowrap;

					.info-list-item {
						display: inline-block;
						padding: 10rpx 37rpx;
						background-color: #ff8123;
						border-radius: 30rpx;
						font-size: 26rpx;
						font-weight: bold;
						color: #ffffff;
						margin-right: 22rpx;
						margin-top: 25rpx;
					}

					.info-list-item:nth-child(2n) {
						background-color: #fdefdd;
						color: #ff8123;
					}
				}

			}
		}

		.box {
			margin-top: 35rpx;

			.box-title {
				display: flex;
				align-items: center;
				padding: 0 14rpx 0 22rpx;

				.name {
					flex: 1;
					font-size: 33rpx;
					font-weight: bold;
					color: #000000;
				}

				.add {
					width: 45rpx;
					height: 45rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.box-content {
				margin-top: 15rpx;
				padding: 35rpx;
				background-color: #ffffff;
				border-radius: 30rpx;
				position: relative;
				overflow: hidden;
			}

			.box-content-bg {
				width: 683rpx;
				height: 419rpx;
				position: absolute;
				left: 0;
				top: 0;
				z-index: 1;
			}

			.table-title {
				display: flex;
				align-items: center;
				margin-top: -25rpx;
				margin-bottom: 10rpx;
				position: relative;
				z-index: 2;

				.table-title-icon {
					width: 45rpx;
					height: 45rpx;
				}

				.table-title-text {
					font-size: 20rpx;
					color: #fd8c06;
					margin-left: 12rpx;
					font-weight: bold;
				}
			}

			.table-container {
				width: 100%;
				border-radius: 10rpx;
				overflow: hidden;
				position: relative;
				z-index: 2;

				.table-header {
					display: flex;
					height: 45rpx;
					padding: 0 20rpx;
					background-color: #ff8516;

					.table-cell {
						flex: 1;
						font-size: 24rpx;
						color: #fff;
						display: flex;
						align-items: center;
						justify-content: center;
						font-weight: bold;
					}
				}

				.table-body {
					border-radius: 0 0 10rpx;
					overflow: hidden;

					.table-row {
						min-height: 87rpx;
						background-color: #fed49a;
						padding: 10rpx 20rpx;
						display: flex;

						.table-cell {
							flex: 1;
							font-size: 24rpx;
							color: #000000;
							display: flex;
							align-items: center;
							justify-content: center;
							font-weight: bold;
						}
					}

					.table-row:nth-child(3n + 1) {
						background-color: #fed49a;
					}

					.table-row:nth-child(3n + 2) {
						background-color: #fee2c4;
					}

					.table-row:nth-child(3n) {
						background-color: #ffeed4;
					}
				}
			}

			.device-item {
				width: 100%;
				height: 110rpx;
				background-color: #f2f2f2;
				border-radius: 20rpx;
				margin-bottom: 22rpx;
				display: flex;
				align-items: center;

				.device-icon {
					width: 109rpx;
					height: 67rpx;
					margin-left: 12rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.device-info {
					flex: 1;
					margin-left: 15rpx;

					.name {
						font-size: 32rpx;
						font-weight: bold;
						color: #fd8c06;
					}

					.number {
						font-size: 22rpx;
						color: #000000;
						margin-top: 7rpx;
					}
				}

				.delete-btn-wrapper {
					width: 120rpx;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;

					.delete-btn {
						width: 100%;
						height: 40rpx;
						border-radius: 30rpx;
						border: 1rpx solid #b7b7b7;
						background-color: #faf0e5;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 20rpx;
						color: #fd8c06;
						margin-right: 14rpx;
					}
				}
			}

			.device-item:last-child {
				margin-bottom: 0;
			}

			.reservation-item {
				width: 100%;
				height: 214rpx;
				padding: 15rpx;
				margin-bottom: 20rpx;
				border-radius: 20rpx;
				background-color: #f5f5f7;

				.title-wrapper {
					width: 389rpx;
					height: 45rpx;
					background: linear-gradient(to right, #f6d7b1, #f5f5f7);
					display: flex;
					align-items: center;
					border-radius: 10rpx;

					.circle {
						width: 12rpx;
						height: 12rpx;
						border-radius: 12rpx;
						background-color: #f79414;
						margin-left: 14rpx;
						margin-right: 9rpx;
					}

					.title {
						font-size: 28rpx;
						color: #f79414;
					}
				}

				.statistics {
					display: flex;
					align-items: center;
					justify-content: space-around;

					.statistics-item {
						flex: 1;
						margin-top: 20rpx;
						display: flex;
						flex-direction: column;
						// padding-left: 62rpx;
						// margin-right: 62rpx;

						.label {
							font-size: 22rpx;
							color: #7b7b7b;
							text-align: center;
						}

						.value-wrapper {
							flex: 1;
							// border: 1rpx solid red;
							display: flex;
							align-items: baseline;
							justify-content: center;
							margin-top: 15rpx;

							.value {
								min-width: 42%;
								// background-color: orange;
								font-size: 60rpx;
								font-weight: bold;
								color: #000000;
								text-align: right;
							}

							.unit {
								font-size: 22rpx;
								color: #7b7b7b;
								margin-left: 10rpx;
							}
						}
					}
				}
			}

			.reservation-item:last-child {
				margin-bottom: 0;
			}

			.manager-item {
				width: 100%;
				height: 110rpx;
				background-color: #f2f2f2;
				border-radius: 20rpx;
				display: flex;
				align-items: center;

				.manager-icon {
					width: 67rpx;
					height: 67rpx;
					margin: 0 30rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.manager-info {
					flex: 1;
					// margin-left: 15rpx;

					.name {
						font-size: 32rpx;
						font-weight: bold;
						color: #fd8c06;
					}

					.number {
						font-size: 22rpx;
						color: #000000;
						margin-top: 7rpx;
					}
				}

				.manager-arrow {
					margin-right: 30rpx;
				}
			}
		}

		.data-null {
			height: 114rpx;
			font-size: 24rpx;
			color: #ff8d28;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #fff;
			border-radius: 20rpx;
		}
	}
</style>